package com.example.servlet;

import com.example.model.Book;
import com.example.model.User;
import com.example.util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/admin-book")
public class AdminBookServlet extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("user");
        
        // 检查是否是管理员
        if (currentUser == null || !"admin".equals(currentUser.getUsername())) {
            response.sendRedirect("login.jsp");
            return;
        }
        
        try (Connection conn = DBUtil.getConnection()) {
            String sql = "SELECT id, name, author, description, price, stock, category, cover_url, create_time, sales FROM books ORDER BY id DESC";
            PreparedStatement stmt = conn.prepareStatement(sql);
            ResultSet rs = stmt.executeQuery();
            
            List<Book> books = new ArrayList<>();
            while (rs.next()) {
                Book book = new Book();
                book.setId(rs.getInt("id"));
                book.setName(rs.getString("name"));
                book.setAuthor(rs.getString("author"));
                book.setDescription(rs.getString("description"));
                book.setPrice(rs.getBigDecimal("price"));
                book.setStock(rs.getInt("stock"));
                book.setCategory(rs.getString("category"));
                book.setCoverUrl(rs.getString("cover_url"));
                book.setCreateTime(rs.getTimestamp("create_time"));
                book.setSales(rs.getInt("sales"));
                books.add(book);
            }
            
            request.setAttribute("books", books);
            request.getRequestDispatcher("admin-book.jsp").forward(request, response);
            
        } catch (SQLException e) {
            e.printStackTrace();
            request.setAttribute("error", "数据库连接错误: " + e.getMessage());
            request.getRequestDispatcher("admin-book.jsp").forward(request, response);
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        doGet(request, response);
    }
} 